package main

import (
	"bufio"
	"chatBot/share"
	"encoding/json"
	"flag"
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"net/url"
	"os"
	"os/signal"
)

var (
	serverIP   string
	serverPort string
	username   string
	token      string
)

func init() {
	flag.StringVar(&serverIP, "h", "127.0.0.1", "服务器IP地址")
	flag.StringVar(&serverPort, "p", "8080", "服务器端口号")
	flag.StringVar(&username, "u", "zhangsan", "用户名")
	flag.StringVar(&token, "token", "token", "token")
}

func main() {
	flag.Parse()

	// 构建WebSocket地址
	u := url.URL{
		Scheme: "ws",
		Host:   fmt.Sprintf("%s:%s", serverIP, serverPort),
		Path:   "/chat",
	}

	log.Printf("connecting to %s", u.String())
	log.Printf("service ip:%v", serverIP)
	log.Printf("service port:%v", serverPort)
	log.Printf("username:%v", username)
	log.Printf("token:%v", token)

	// 创建连接
	dialer := websocket.DefaultDialer
	conn, _, err := dialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("连接失败:", err)
	}
	defer conn.Close()
	log.Printf("已成功连接到 %s", u.String())

	// 发送握手包
	handshake := share.HandshakeReq{
		Version:  "1.0",
		Username: username,
		Token:    token,
	}
	if err := conn.WriteJSON(handshake); err != nil {
		log.Fatal("握手包发送失败:", err)
	}

	// 等待握手响应
	_, response, err := conn.ReadMessage()
	if err != nil {
		log.Fatal("握手响应接收失败:", err)
	}

	resp := share.HandshakeResp{}
	if json.Unmarshal(response, &resp) != nil || resp.Status != 200 {
		log.Fatal("握手失败:", string(response))
	}
	log.Println("握手成功:", resp.Message)

	// 信号处理
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)

	// 创建通信通道
	done := make(chan struct{})

	// 启动消息接收协程
	go func() {
		defer close(done)
		for {
			_, message, err := conn.ReadMessage()
			if err != nil {
				log.Println("接收错误:", err)
				return
			}
			fmt.Printf("服务器回复: %s\n\n输入消息 > ", message)
		}
	}()

	// 启动输入处理协程
	go func() {
		reader := bufio.NewReader(os.Stdin)
		fmt.Print("输入消息 > ")
		for {

			text, _ := reader.ReadString('\n')

			if len(text) == 0 {
				break
			}

			// 构造消息
			msg := struct {
				Content string `json:"content"`
			}{
				Content: text[:len(text)-1], // 去除换行符
			}

			// 发送JSON消息
			if err := conn.WriteJSON(msg); err != nil {
				log.Println("发送失败:", err)
				return
			}
		}
	}()

	// 主循环
	for {
		select {
		case <-done:
			return
		case <-interrupt:
			log.Println("收到中断信号，关闭连接...")

			return
		}
	}
}
